package cn.itrip.auth.service.impl;

import cn.itrip.auth.service.TokenService;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.common.MD5;
import cn.itrip.common.RedisAPI;
import cn.itrip.common.UserAgentUtil;
import com.alibaba.fastjson.JSON;
import nl.bitwalker.useragentutils.UserAgent;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Service
public class TokenServiceImpl implements TokenService {
    @Resource
    private RedisAPI redisAPI;
    @Override
    public String geterateToken(String userAgent, ItripUser user) throws Exception {
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("token:");
        UserAgent agent=UserAgent.parseUserAgentString(userAgent);
        if(agent.getOperatingSystem().isMobileDevice()){
            stringBuilder.append("MOBILE-");
        }else {
            stringBuilder.append("PC-");
        }
        stringBuilder.append(MD5.getMd5(user.getUserCode(),32)+"-");
        stringBuilder.append(user.getId().toString()+"-");
        stringBuilder.append(new SimpleDateFormat("yyyyMMddHHmmsss").format(new Date())+"-");
        stringBuilder.append(MD5.getMd5(userAgent,6));
        return stringBuilder.toString() ;
    }

    @Override
    public void save(String token,ItripUser user) throws Exception {
        if(token.startsWith("token:PC-")){
            redisAPI.set(token,2*60*60, JSON.toJSONString(user));
        }else {
            redisAPI.set(token,JSON.toJSONString(user));
        }
    }

    @Override
    public boolean validate(String userAgent, String token) throws Exception {
        if (!redisAPI.exist(token)){//验证是否存在
            return false;
        }
        String agentMD5=token.split("-")[4];
        System.out.println(MD5.getMd5(userAgent,6));
        if (!MD5.getMd5(userAgent,6).equals(agentMD5)){//验证是不是同浏览器
            return false;
        }
        return true;
    }

    @Override
    public void delete(String token) throws Exception {
        redisAPI.delete(token);
    }

    private long protectedTime =30*60*1000;
    private int delay=2*60;
    @Override
    public String reloadToken(String userAgent,String token) throws Exception {
        if (!redisAPI.exist(token)){//验证token是否有效
            throw new Exception("token无效");
        }
        Date genTime = new SimpleDateFormat("yyyyMMddHHmmsss").parse(token.split("-")[3]);
        long passed = Calendar.getInstance().getTimeInMillis()-genTime.getTime();//生成时间
        if (passed<protectedTime){//验证能不能置换
            throw new Exception("token置换保护期内，不能置换，剩余:"+(protectedTime-passed)/1000);
        }
        String user = redisAPI.get(token);
        ItripUser itripUser = JSON.parseObject(user, ItripUser.class);
        String newToken = this.geterateToken(userAgent,itripUser);//创建新token

        redisAPI.set(token,delay,user);//老token延时
        this.save(newToken,itripUser);//新token保存
        return newToken;
    }
}
